﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml.Serialization;

namespace TestTasks.Cataloguer
{
    public class XmlLoader
    {
        public void Load(string fileName, ICatalogue catalogue) 
        {
            var records = Load<List<XmlRecord>>(fileName);
            foreach (var record in records)
            {
                var doc = new DictionaryDocument();
                if (record.Author != null) doc.Core.Add("Author", record.Author);
                if (record.CreationDate != null) doc.Core.Add("CreationDate", record.CreationDate.Value);
                if (record.Name != null) doc.Core.Add("Name", record.Name);
                if (record.Text != null) doc.Core.Add("Text", record.Text);
                catalogue.Add(doc);
            }
        }

        public void Save(string fileName, ICatalogue catalogue) 
        {
            var records = new List<XmlRecord>();
            foreach (var doc in catalogue)
            {
                var record = new XmlRecord();
                if (doc.HasSet("Author")) record.Author = (string)doc.Get("Author");
                if (doc.HasSet("CreationDate")) record.CreationDate = (DateTime)doc.Get("CreationDate");
                if (doc.HasSet("Name")) record.Name = (string)doc.Get("Name");
                if (doc.HasSet("Text")) record.Text = (string)doc.Get("Text");
                records.Add(record);
            }
            Save(records, fileName);
        }


        void Save<T>(T self, string path)
        {
            using (var file = new FileStream(path, FileMode.CreateNew))
            {
                var serializer = new XmlSerializer(typeof(T));
                serializer.Serialize(file, self);
            }
        }

        T Load<T>(string path)
        {
            using (var file = new FileStream(path, FileMode.Open))
            {
                var serializer = new XmlSerializer(typeof(T));
                return (T)serializer.Deserialize(file);
            }
        }
    }
}
